# -*- coding: utf-8 -*-
from datetime import datetime

from django.http import QueryDict
from django.utils.deprecation import MiddlewareMixin

from gis.common import track_logging

_LOGGER = track_logging.getLogger(__name__)


def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


class TrackLoggerMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """打印request进入时的log"""

        try:

            request.DATA = QueryDict('')
            if request.method == 'GET':
                body = request.META['QUERY_STRING']
            else:
                body = request.body.decode()

            request.incoming_time = datetime.now()
            request.ip = get_client_ip(request)

            track_logging.clear_trace()

            _LOGGER.info("%s - %s, DATA: %s, IP: %s" % (
                request.method.upper(), request.path, body, request.ip))
        except:
            _LOGGER.exception('middleware process view fail')

    def process_exception(self, request, exception):
        pass

    def process_response(self, request, response):
        try:
            duration = int((datetime.now() - request.incoming_time).total_seconds() * 1000)
            _LOGGER.info("URL: {method}: {api_url}, Duration:{duration}".format(
                method=request.method.upper(), api_url=request.path, duration=duration))
        except:
            _LOGGER.exception('middleware process response fail')
        return response
